require.paths.push(__dirname + "/../../libs");
sys = require("sys"),
        debug = require('util').debug,
        inspect = require('util').inspect,
        test = require("assert");

var Db = require('mongodb').Db,
        Connection = require('mongodb').Connection,
        Server = require('mongodb').Server,
        BSON = require('mongodb').BSONNative;

var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT;

sys.puts("Connecting to " + host + ":" + port);

//To enable the driver to use the C/C++ bson parser pass it the option native_parser:true

EntityManager = function() {
  this.db= new Db('demo-db', new Server(host, port, {native_parser:false,auto_reconnect: true}, {}));
  this.db.open(function(){});
};

EntityManager.prototype.getCollection= function(callback) {
  this.db.collection('entites', function(error, entity_collection) {
    if( error ) callback(error);
    else callback(null, entity_collection);
  });
};

EntityManager.prototype.findAll = function(callback) {
    this.getCollection(function(error, entity_collection) {
      if( error ) callback(error)
      else {
        entity_collection.find(function(error, cursor) {
          if( error ) callback(error)
          else {
            cursor.toArray(function(error, results) {
              if( error ) callback(error)
              else callback(null, results)
            });
          }
        });
      }
    });
};

EntityManager.prototype.findById = function(id, callback) {
    this.getCollection(function(error, entity_collection) {
      if( error ) callback(error)
      else {
        entity_collection.findOne({_id: ObjectID.createFromHexString(id)}, function(error, result) {
          if( error ) callback(error)
          else callback(null, result)
        });
      }
    });
};

EntityManager.prototype.save = function(entitys, callback) {
    this.getCollection(function(error, entity_collection) {
      if( error ) callback(error)
      else {
        if( typeof(entitys.length)=="undefined")
          entitys = [entitys];

        for( var i =0;i< entitys.length;i++ ) {
          entity = entitys[i];
          entity.created_at = new Date();
          if( entity.comments === undefined ) entity.comments = [];
          for(var j =0;j< entity.comments.length; j++) {
            entity.comments[j].created_at = new Date();
          }
        }

        entity_collection.insert(entitys, function() {
          callback(null, entitys);
        });
      }
    });
};

exports.EntityManager = EntityManager;